package com.tonann.web.controller.system;

import com.tonann.common.annotation.Log;
import com.tonann.common.constant.UserConstants;
import com.tonann.common.core.controller.BaseController;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.common.core.domain.entity.SysPlace;
import com.tonann.common.enums.BusinessType;
import com.tonann.common.utils.StringUtils;
import com.tonann.system.service.ISysPlaceService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 空间位置信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/place")
public class SysPlaceController extends BaseController
{
    @Autowired
    private ISysPlaceService placeService;

    /**
     * 获取空间位置列表
     */
    @PreAuthorize("@ss.hasPermi('system:place:list')")
    @GetMapping("/list")
    public AjaxResult list(SysPlace place)
    {
        List<SysPlace> places = placeService.selectPlaceList(place);
        return AjaxResult.success(places);
    }

    /**
     * 查询空间位置列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:place:list')")
    @GetMapping("/list/exclude/{placeId}")
    public AjaxResult excludeChild(@PathVariable(value = "placeId", required = false) Long placeId)
    {
        List<SysPlace> places = placeService.selectPlaceList(new SysPlace());
        places.removeIf(d -> d.getPlaceId().intValue() == placeId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), placeId + ""));
        return AjaxResult.success(places);
    }

    /**
     * 根据空间位置编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:place:query')")
    @GetMapping(value = "/{placeId}")
    public AjaxResult getInfo(@PathVariable Long placeId)
    {
        placeService.checkPlaceDataScope(placeId);
        return AjaxResult.success(placeService.selectPlaceById(placeId));
    }

    /**
     * 新增空间位置
     */
    @PreAuthorize("@ss.hasPermi('system:place:add')")
    @Log(title = "空间位置管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPlace place)
    {
        if (UserConstants.NOT_UNIQUE.equals(placeService.checkPlaceNameUnique(place)))
        {
            return AjaxResult.error("新增空间位置'" + place.getPlaceName() + "'失败，空间位置名称已存在");
        }
        place.setCreateBy(getUsername());
        return toAjax(placeService.insertPlace(place));
    }

    /**
     * 修改空间位置
     */
    @PreAuthorize("@ss.hasPermi('system:place:edit')")
    @Log(title = "空间位置管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPlace place)
    {
        Long placeId = place.getPlaceId();
        placeService.checkPlaceDataScope(placeId);
        if (UserConstants.NOT_UNIQUE.equals(placeService.checkPlaceNameUnique(place)))
        {
            return AjaxResult.error("修改空间位置'" + place.getPlaceName() + "'失败，空间位置名称已存在");
        }
        else if (place.getParentId().equals(placeId))
        {
            return AjaxResult.error("修改空间位置'" + place.getPlaceName() + "'失败，上级空间位置不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, place.getStatus()) && placeService.selectNormalChildrenPlaceById(placeId) > 0)
        {
            return AjaxResult.error("该空间位置包含未停用的子空间位置！");
        }
        place.setUpdateBy(getUsername());
        return toAjax(placeService.updatePlace(place));
    }

    /**
     * 删除空间位置
     */
    @PreAuthorize("@ss.hasPermi('system:place:remove')")
    @Log(title = "空间位置管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{placeId}")
    public AjaxResult remove(@PathVariable Long placeId)
    {
        if (placeService.hasChildByPlaceId(placeId))
        {
            return AjaxResult.error("存在下级空间位置,不允许删除");
        }
        if (placeService.checkPlaceExistUser(placeId))
        {
            return AjaxResult.error("空间位置存在用户,不允许删除");
        }
        placeService.checkPlaceDataScope(placeId);
        return toAjax(placeService.deletePlaceById(placeId));
    }
}
